<?php

namespace app\admin\controller;

use PDOException;
use think\Db;
use think\Exception;
use think\exception\ValidateException;

class Backend extends Common
{

    protected $with = null;

    /**
     * 列表
     * @return mixed
     */
    public function index()
    {
        $this->existModel();
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();

        $list = $this->model
            ->with($this->with ? $this->with : null)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function delete($id)
    {
        $this->existModel();
        $error = '';
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if ($v <= 0) {
                    $error .= '参数传递错误[' . $v . ']！<br>';
                    continue;
                }
                $map = [];
                $map['id'] = $v;
                try {
                    $this->model->where($map)->delete();
                } catch (Exception $e) {
                    $error .= $e->getMessage();
                }
            }
            if ($error) {
                $this->error($error);
            }
        } else {
            if ($id <= 0) {
                $error .= '参数传递错误[' . $id . ']！<br>';
            }
            $map = ['id' => $id];

            try {
                $this->model->where($map)->delete();
            } catch (Exception $e) {
                $error .= $e->getMessage();
            }
            if ($error) {
                $this->error($error);
            }
        }
        $this->success('删除成功');
    }

    public function create()
    {
        $this->existModel();
        return $this->fetch('new');
    }

    public function save()
    {
        $params = $this->post();
        $this->model->insert($params)->save();
    }

    /**
     * 编辑
     */
    public function edit($id = null)
    {
        $row = $this->model->with($this->with == null ? [] : $this->with)->find($id);
        if (!$row) {
            $this->error('记录不存在');
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $result = false;
                if ($this->company) {
                    $company = $this->company;
                    $params['company_id'] = $company->id;
                }
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                    if ($this->request->isAjax()) {
                        $this->success("更新成功");
                    }
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success("成功");
                } else {
                    $this->error('未更新');
                }
            }
            $this->error('Parameter %s can not be empty');
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 添加实体数据
     * @return mixed
     */
    public function add($id = null)
    {
        $this->existModel();
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if ($this->company) {
                $data['company_id'] = $this->company->id;
            }
            $result = false;
            Db::startTrans();
            try {
                $result = $this->model->allowField(true)->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success("成功");
            } else {
                $this->error($this->model->getError());
            }
        }
        return $this->fetch();
    }

    /**
     * 获取实体数据
     * @param null $id
     * @return string
     * @throws \think\Exception
     */
    public function show($id = null)
    {
        $this->existModel();
        $row = $this->model->with($this->with ? $this->with : [])->find($id);
        if (!$row) {
            $this->error("资源不存在！");
        }
        if ($this->request->isAjax()) {
            $this->success("", null, $row);
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    protected function existModel()
    {
        if (!$this->model) {
            throw new Exception('模型不存在');
        }
        return $this->model && class_exists($this->model);
    }

    /**
     * 资源没找到
     * @param string $msg
     */
    protected function notFound($msg = '资源不存在')
    {
        $this->error($msg);
    }

    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? (isset($this->searchFields) ? $this->searchFields : $searchfields) : $searchfields;
//        $relationSearch = is_null($relationSearch) ? (isset($this->relationSearch) ? $this->relationSearch : $relationSearch) : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 15);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
//        if (!empty($this->model) && $this->relationSearch) {
//            $name = $this->model->getTable();
//            $alias[$name] = Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
//            $aliasName = $alias[$name] . '.';
//        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "%{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }
}